<?php

namespace Admin\Logic;

use Common\Model\ContractModel;

class ContractLogic extends ContractModel 
{

	protected function _initialize() 
	{
		parent::_initialize();
	}
	
	public function responseByHttp($uri,$data,$method)
	{
		$method = strtoupper($method);
		 
		$ch = curl_init();
	
		curl_setopt($ch, CURLOPT_URL, $uri);
	
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	
		curl_setopt($ch, CURLOPT_HEADER, false);//不返回头部信息
	
		curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/xml','Content-Length: ' . strlen($data),'charset=utf-8'));
	
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0);
		 
		if( $method == 'POST')
		{
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POST,true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
	
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
	
		//暂不下载证书
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	
		//执行curl
		$output = curl_exec($ch);
	
		//错误提示
		if(curl_exec($ch) === false){
			die(curl_error($ch));
		}
		// 检查是否有错误发生
		if(curl_errno($ch)){
			echo 'Curl error: ' . curl_error($ch);
		}
	
		//释放curl句柄
		curl_close($ch);
	
		return $output;
	}

	public function getPage($where = array(), &$pageShow = null, $pageSize = 10, $parameter = array()) 
	{	
		$sql = $this->getSql($where);
		
		$totalRows = $this->where($sql)->count();
		
		$this->order('contract_id DESC');
		
		$data = $this->where($sql)->pagination($totalRows, $pageShow, $pageSize, $parameter)->getItems();
		
		foreach ($data as $key => &$item) 
		{
			$item['status'] = get_format_state($item['contract_status'],array('未支付','支付成功.text-green','支付失败.text-red'));
			$item['time'] = get_format_date($item['contract_time']);
			$item['amount']  = get_format_money($item['contract_amount']/100);
			$item['detail'] = get_format_url('detail', $item['contract_id']);
			$item['edit'] = get_format_url('edit', $item['contract_id']);
			$item['delete'] = get_format_url('delete', $item['contract_id']);
			$item['query'] = get_format_url('query');
		}

		return $data;
	}

	public function getDownload($where = array(),$order = '')
	{
		$sql = $this->getSql($where);
		
		$this->order('contract_id DESC');
		
		$data = $this->where($sql)->getItems();
		
		$raw = array();

		foreach ($data as $key => $item){
			$status = '未支付';
			if ($item['contract_status']==1) {
				$status = '支付成功';
			}
			if($item['contract_status']==2){
				$status = '支付失败';
			}
			$raw[] = array(
					'contract_number' =>'\''.$item['contract_number'],
					'contract_transaction_id' =>empty($item['contract_transaction_id']) ? '': '\''.$item['contract_transaction_id'],
					'contract_name' => $item['contract_name'],
					'contract_cardid' =>empty($item['contract_cardid']) ? '' : '\''.$item['contract_cardid'],
					'contract_amount' => $item['contract_amount']/100,
					'contract_time' => get_format_date($item['contract_time'],'Y年m月d日 H:i:s'),
					'contract_loan_type' => $item['contract_loan_type'],
					'contract_commodity_type' => $item['contract_commodity_type'],
					'contract_brand' => $item['contract_brand'],
					'contract_total_money' => $item['contract_total_money'],
					'contract_down_pay' => $item['contract_down_pay'],
					'contract_status' => $status,
			);
		}
		return $raw;
	}

	public function updateContract($data = array())
	{
		$data = $this->create($data);
		
		$map = array(
				'status' => 0,
		);
		
		$data = completion($data, $map);
		
		$data['contract_amount'] = $data['contract_amount'] * 100;
		
		$data['contract_time'] = empty($data['contract_time']) === false ? strtotime($data['contract_time']) : time();
		
		return $this->updateRecord($data);
	}

	public function getEdit($pk = 0) 
	{
		$data = $this->getItem($pk);
		
		// 调整时间，支付金额格式
		$data['time'] = empty($data['contract_time']) === false ? date('Y-m-d H:i:s',$data['contract_time']) : NULL;
		
		$data['amount']  = $data['contract_amount']/100;
		
		return $data;
	}

	public function deleteByPK($pk = 0) 
	{
		return $this->deleteRecord($pk);
	}
	
	protected function getSql($where = array())
	{
		$sql = '';
		
		$where['start_time'] = empty($where['start_time']) == false ? $where['start_time']:'2017-01-01';
		
		$where['end_time'] = empty($where['end_time']) == false ? $where['end_time'] : date("Y-m-d H:i:s",time());
		
		$sql .= '( contract_time BETWEEN ' . strtotime($where["start_time"]) . ' AND ' . (strtotime($where["end_time"])+86400);
		
		$sql .= " OR (contract_time IS NULL) )";
		
		if( !empty($sql) )
		{
			if( $where['status'] !== 'all' )
			{
				$sql .= ' AND contract_status = ' . I('get.status');
			}
		}
		
		$sql .= empty($where['name']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_name)',$where['name']).')';
		
		$sql .= empty($where['number']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_number)',$where['number']).')';
		
		$sql .= empty($where['cardid']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_cardid)',$where['cardid']).')';
		
		$sql .= empty($where['transaction_id']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_transaction_id)',$where['transaction_id']).')';
		
		return $sql;
	}
	
	public function getAllStatus()
	{
		return array(
				1=>'支付成功',
				0=>'未支付',
				2=>'支付失败',
		);
	}

}


